import 'dart:convert';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/viewmode/mine_notification_viewmodel.dart';
import 'package:loxen/dialog/loading.dart' as dialog;
import 'package:loxen/widget/loading_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/mode/mine/mine_information_mode.dart';
import 'package:loxen/viewmode/mine_page_viewmodel.dart';

class MineCover extends StatelessWidget {
  final ValueNotifier<bool> staff = ValueNotifier(false);

  MineCover({Key key}) : super(key: key);

  _selectAvatar(BuildContext context) async {
    var data = await _chicePhoto(context);
    var _imgPath;
    if (data != null && data == 'Photo') {
      var image = await ImagePicker().getImage(source: ImageSource.camera, imageQuality: 50);
      _imgPath = image;
    } else if (data != null && data == 'Gallery') {
      var image = await ImagePicker().getImage(source: ImageSource.gallery, imageQuality: 50);
      _imgPath = image;
    } else {
      return false;
    }

    String fileName = _imgPath.path.split('/').last;

    FormData formData = FormData.fromMap({
      "background": await MultipartFile.fromFile(
        _imgPath.path,
        filename: fileName,
      ),
    });
    Provider.of<MinePageViewModel>(context, listen: false).modifyBackground(formData, success: () {
      _imgPath = null;
      Toast.show('上传成功', context);
    }, onError: (error) {
      _imgPath = null;
      Toast.show('上传失败', context);
    });
  }

  void scanData(BuildContext context, String json) async {
    try {
      var data = JsonDecoder().convert(json);
      if (data is Map) {
        if (data['mode'] == '2') {
          int id = data['data']['department_id'];
          int centerId = data['data']['service_centre_id'];
          String name = await showDialog(
              context: context,
              builder: (context) {
                TextEditingController controller = TextEditingController();
                return AlertDialog(
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(bottom: 30.h),
                        alignment: Alignment.topLeft,
                        child: Text(
                          StringResources.shen_qing_ye_wu_yuan,
                          style: TextStyle(
                            fontSize: 32.sp,
                            fontWeight: FontWeight.bold,
                            color: Theme.of(context).textTheme.subtitle2.color,
                          ),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.only(
                          top: 6.h,
                          bottom: 6.h,
                        ),
                        decoration: BoxDecoration(border: Border.all(color: Color(0xFF999999))),
                        child: TextField(
                          controller: controller,
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: Theme.of(context).textTheme.subtitle2.color,
                          ),
                          decoration: InputDecoration(
                            hintText: "请输入真实姓名",
                            border: InputBorder.none,
                            isDense: true,
                          ),
                        ),
                      ),
                    ],
                  ),
                  actions: <Widget>[
                    FlatButton(
                      child: Text(StringResources.qu_xiao),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                    FlatButton(
                      child: Text(StringResources.que_ding),
                      onPressed: () {
                        if (controller.text.trim() != '') {
                          Navigator.of(context).pop(controller.text);
                        } else {
                          Toast.show("姓名不能为空", context);
                        }
                      },
                    ),
                  ],
                );
              });
          dialog.Loading.createView('加载中', context);
          ApiService.applyStaff(name, centerId, departmentId: id).listen((event) {
            Toast.show('申请成功', context);
          }, onError: (error, stack) {
            Toast.show('申请失败', context);
          }, onDone: () {
            dialog.Loading.dismiss();
          });
        } else if (data['mode'] == '1') {
          String uid = data['uid'];
          dialog.Loading.createView('加载中', context);
          ApiService.qrLogin(uid).listen((event) {
            Toast.show('登录成功', context);
          }, onError: (error, stack) {
            Toast.show('登录失败', context);
          }, onDone: () {
            dialog.Loading.dismiss();
          });
        }
      } else {
        Toast.show('解析数据失败', context);
      }
    } catch (error) {
      Toast.show('解析数据失败', context);
    }
  }

  _chicePhoto(BuildContext context) async {
    return await showModalBottomSheet(
      context: context,
      elevation: 0,
      builder: (context) {
        return Container(
          height: 190,
          child: ListView(
            children: <Widget>[
              _renderContainer(
                  text: '请选择照片或拍照', fontSize: 14, textColor: Color(0xFF82868E), hasBorder: true),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 'Photo');
                },
                child: _renderContainer(
                  text: '拍照',
                  fontSize: 16,
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context, 'Gallery');
                },
                child: _renderContainer(
                  text: '照片',
                  fontSize: 16,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _renderContainer(
      {String text,
      Color bgc = Colors.white,
      bool hasBorder = false,
      Color textColor = const Color(0xFF000000),
      double fontSize = 16}) {
    return Container(
      height: 63,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: bgc,
          border:
              Border(bottom: BorderSide(color: Color(0xFFF6F6F7), width: hasBorder ? 0.5 : 0.0))),
      child: Text(text,
          style: TextStyle(
            color: textColor,
            fontWeight: FontWeight.w500,
            fontSize: fontSize,
            height: 1,
          )),
    );
  }

  @override
  Widget build(BuildContext context) {
    ApiService.isStaff().listen((event) {
      var data = event.data['data']['is_staff'];
      if (data is bool) {
        staff.value = data;
      }
    }, onError: (error, stack) {
      print(error);
      print(stack);
    });
    var state = context.select<MinePageViewModel, BaseState>((value) => value.mState);
    if (state == BaseState.FAIL || state == BaseState.CONTENT) {
      MineInformation detail = Provider.of<MinePageViewModel>(context, listen: false).data;
      bool isLogin = !Provider.of<LoginViewModel>(context, listen: false).isLogin();
      return Container(
        height: 500.h,
        child: Stack(
          children: [
            Builder(builder: (context) {
              if (isLogin && detail != null) {
                return CachedNetworkImage(
                  imageUrl: ImageUrlUtil.getClean(detail.user.background),
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                );
              } else {
                return Image.asset(
                  'images/mine_default_cover@.png',
                  width: double.infinity,
                  height: double.infinity,
                  fit: BoxFit.cover,
                );
              }
            }),
            Container(
              color: Color(0x32000000),
            ),
            Container(
              width: double.infinity,
              child: Column(
                children: [
                  (isLogin && detail != null)
                      ? Padding(
                          padding: EdgeInsets.only(top: 60.h, left: 40.w, right: 38.w),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                onTap: () {
                                  if (isLogin) {
                                    Navigator.of(context).pushNamed(Routes.mineMsg);
                                    Provider.of<MineNotificationViewModel>(context, listen: false)
                                        .setNotification(false);
                                  } else {
                                    Navigator.of(context).pushNamed(Routes.login_page);
                                  }
                                },
                                child: Stack(
                                  alignment: Alignment.center,
                                  children: <Widget>[
                                    Image.asset('images/mine_remind@2x.png', width: 25),
                                    Selector<MineNotificationViewModel, bool>(
                                      builder: (_, hasNotification, __) {
                                        if (hasNotification) {
                                          return Positioned(
                                            top: 1,
                                            right: 3,
                                            child: Container(
                                              width: 8,
                                              height: 8,
                                              decoration: BoxDecoration(
                                                  color: Colors.red,
                                                  borderRadius: BorderRadius.circular(100.0)),
                                            ),
                                          );
                                        }
                                        return Constants.empty;
                                      },
                                      selector: (_, model) => model.hasNotification,
                                    )
                                  ],
                                ),
                              ),
                              Expanded(child: Constants.empty),
                              isLogin
                                  ? Padding(
                                      padding: EdgeInsets.only(right: 40.w),
                                      child: GestureDetector(
                                        onTap: () async {
                                          var options = ScanOptions(
                                            strings: {
                                              'flash_on': '打开灯光',
                                              'flash_off': '关闭灯光',
                                              'cancel': '关闭',
                                            },
                                            // set the options
                                          );
                                          ScanResult result =
                                              await BarcodeScanner.scan(options: options);
                                          if (result.type.value == ResultType.Barcode.value) {
                                            scanData(context, result.rawContent);
                                          }
                                        },
                                        child: Image.asset(
                                          'images/qr_icon.png',
                                          width: 36.w,
                                          height: 36.w,
                                        ),
                                      ),
                                    )
                                  : SizedBox.shrink(),
                              isLogin
                                  ? GestureDetector(
                                      onTap: () {
                                        _selectAvatar(context);
                                      },
                                      child: Image.asset(
                                        'images/mine_photo@2x.png',
                                        height: 36.w,
                                        fit: BoxFit.fitHeight,
                                      ),
                                    )
                                  : SizedBox.shrink()
                            ],
                          ),
                        )
                      : Padding(
                          padding: EdgeInsets.only(top: 96.h),
                          child: Constants.empty,
                        ),
                  Builder(
                    builder: (BuildContext context) {
                      String url = context.select<MinePageViewModel, String>(
                          (value) => value?.data?.user?.portrait);
                      if (isLogin && detail != null) {
                        return Padding(
                          padding: EdgeInsets.only(top: 20.h),
                          child: GestureDetector(
                            onTap: () {
                              Navigator.of(context)
                                  .pushNamed(Routes.mineInfoEdit, arguments: detail.user)
                                  .then((value) {
                                Provider.of<MinePageViewModel>(context, listen: false)
                                    .changeEntity();
                              });
                            },
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(160.w),
                              child: CachedNetworkImage(
                                imageUrl: ImageUrlUtil.getClean(url, w: 160),
                                height: 160.w,
                                width: 160.w,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        );
                      } else {
                        return Padding(
                          padding: EdgeInsets.only(top: 20.h),
                          child: GestureDetector(
                            onTap: () {
                              Navigator.of(context).pushNamed(Routes.login_page);
                            },
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(160.w),
                              child: Image.asset(
                                'images/mine_default_avatar@2x.png',
                                height: 160.w,
                                width: 160.w,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        );
                      }
                    },
                  ),
                  Builder(builder: (context) {
                    String nickName;
                    if (isLogin && detail != null) {
                      nickName = context.select<MinePageViewModel, String>(
                          (value) => value?.data?.user?.nickname);
                    } else {
                      nickName = '请登录';
                    }
                    return Padding(
                      padding: EdgeInsets.only(top: 10.h),
                      child: Text(
                        nickName,
                        style: TextStyle(fontSize: 30.sp, color: Colors.white),
                      ),
                    );
                  }),
                  ValueListenableProvider.value(
                    value: staff,
                    builder: (context, _) {
                      var staff = context.watch<bool>();
                      if (isLogin && detail != null && staff) {
                        return Padding(
                          padding: EdgeInsets.only(top: 10.h),
                          child: Material(
                            borderRadius: BorderRadius.all(Radius.circular(35.h)),
                            color: Color(0x7F000000),
                            child: InkWell(
                              onTap: () {
                                Provider.of<MinePageViewModel>(context, listen: false)
                                    .changeStaff();
                              },
                              borderRadius: BorderRadius.all(Radius.circular(35.w)),
                              child: Container(
                                width: 110.w,
                                height: 35.h,
                                child: Center(
                                  child: Text(
                                    '切换角色',
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      color: Color(0xFFFCAE08),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        );
                      } else {
                        return Padding(
                          padding: EdgeInsets.only(top: 45.h),
                          child: Constants.empty,
                        );
                      }
                    },
                  ),
                  (isLogin && detail != null)
                      ? Padding(
                          padding: EdgeInsets.only(top: 18.h),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  Text(
                                    '${detail.like_num}',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 32.sp,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Text('获赞',
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 24.sp,
                                          fontWeight: FontWeight.w500))
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Text(
                                    '${detail.follow_num}',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 32.sp,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Text('人气',
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 24.sp,
                                          fontWeight: FontWeight.w500))
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Text(
                                    '${detail.comment_num}',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 32.sp,
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Text('评论',
                                      style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 24.sp,
                                          fontWeight: FontWeight.w500))
                                ],
                              )
                            ],
                          ),
                        )
                      : Constants.empty,
                ],
              ),
            )
          ],
        ),
      );
    } else {
      return LoadingWidget();
    }
  }
}
